<?php
class YWSPermissions {
    public static function hasPermission($username, $controller, $action, $module = null) {
        // Super User checking
        if (YWSMembership::IsSuper($username)) return true;
        
        // Create the namespace - with lowercase
        $namespace = strtolower(YWSUtils::createNameSpace($controller, $action, $module));
        // Get Userinfo
        $user = YWSMembership::getUserByUsername($username);
        // Get Roles of current user
        $roles = YWSMembership::getRoles($user['id']);
        // Get the permission based on ACTION. Returns the role-ID to check
        $permissions = Yii::app()->db->createCommand()
                ->select()
                ->from(PortalPermissions::model()->tableName())
                        ->where("action = '$namespace'")
                ->queryAll();
        
//        var_dump($roles);
//        var_dump($permissions);
        
        // If no permission is found return false
        if (count($permissions) == 0) return false;
        
        // Checking permission. If records in $permissions exists, return TRUE
        for($i = 0; $i < count($roles); $i++) {
            for ($j = 0; $j < count($permissions); $j++) {
                // if match one return true
                if (in_array($roles[$i]['role_id'], $permissions[$j])) return true;
            }
        }
        
        return false;
    }
}
?>